/**
 * ZHU framework. Copyright 2012-, all rights reserved.
 *
 * $Id: AbstractWebRequestContext.java 24 2012-08-17 07:21:26Z zhuxiaopeng $
 * $Revision: 24 $
 * $Date: 2012-08-17 15:21:26 +0800 (五, 2012-08-17) $
 * $Author: zhuxiaopeng $
 */
package zhu.framework.web;

import java.io.*;
import java.net.*;
import java.util.logging.*;

import javax.servlet.http.*;

import zhu.framework.service.*;
import zhu.framework.util.*;

/**
 * <p>
 * </p>
 * 
 * @author $Author: zhuxiaopeng $
 * @version $Revision: 24 $ - $Date: 2012-08-17 15:21:26 +0800 (五, 2012-08-17) $
 */
public abstract class AbstractWebRequestContext implements WebRequestContext {

	/**
	 * このClassのデフォルトの<code>Logger</code>取得する。
	 * 特に理由のない限り、このClass内ではこのメソッドを通じてLoggerを取得することを推奨する。
	 * 
	 * @return このClassのデフォルトの<code>Logger</code>
	 */
	static private Logger getLogger() {
		final LoggerManager manager = LoggerManager.getInstance();
		final Logger logger = manager.getLogger(AbstractWebRequestContext.class);
		return logger;
	}

	public AbstractWebRequestContext(final ServiceRequestContext serviceRequestContext, final WebSessionContext sessionContext) {
		MyUtility.checkMethodParameterNotNull("serviceRequestContext", serviceRequestContext);
		MyUtility.checkMethodParameterNotNull("sessionContext", sessionContext);
		//
		this.serviceRequestContext = serviceRequestContext;
		this.sessionContext = sessionContext;
	}

	@Override
	public final ServiceRequestContext getServiceRequestContext() {
		return serviceRequestContext;
	}

	@Override
	public WebSessionContext getSessionContext() {
		return this.sessionContext;
	}

	@Override
	public OutputStream openDownloadStream(final WebDownloadContext downloadContext) throws IOException {
		MyUtility.checkMethodParameterNotNull("downloadContext", downloadContext);
		//
		final Logger logger = getLogger();
		if (logger.isLoggable(Level.FINE)) {
			logger.fine(String.format("Opening a download session with : %s", downloadContext));
		}
		//
		downloadContext.setReadonly();
		//
		final HttpServletResponse response = (HttpServletResponse) this.getResponse();
		response.setContentType(downloadContext.getContentType());
		if (downloadContext.getFilename() != null) {
			final String dispositionHeaderValue = String.format("%s; filename=\"%s\"", downloadContext.getContentDispositionType()
					.getTypeForHttpHeader(), URLEncoder.encode(downloadContext.getFilename(), downloadContext.getFilenameEncoding()));
			response.setHeader("Content-Disposition", dispositionHeaderValue);
			//
			if (logger.isLoggable(Level.FINEST)) {
				logger.finest(String.format("Content-Disposition header value is : %s", dispositionHeaderValue));
			}
		}
		return response.getOutputStream();
	}

	private final ServiceRequestContext serviceRequestContext;
	private final WebSessionContext sessionContext;

}
